import {
  SPUCreateDto,
  SPUFindDto,
  SPUListDto,
  SPUQueryDto,
  SPUUpdateDto,
} from '@/dtos';
import { SPUService } from '@/services/spu.service';
import { halt, ok } from '@/utils';
import { Body, Controller, Get, Param, Patch, Post } from '@nestjs/common';
import { BaseController } from './base.controller';

@Controller('spu')
export class SPUController extends BaseController {
  constructor(private readonly spuService: SPUService) {
    super();
  }

  @Post('list')
  async list(@Body() dto: SPUListDto) {
    return ok(await this.spuService.list(dto));
  }

  @Get('detail/:id')
  async getDetail(@Param('id') id: number) {
    const data = (await this.spuService.findOne(
      {
        id,
        isDeleted: false,
      },
      {
        id: true,
        title: true,
        image: true,
        price: true,
        startSaleNum: true,
        stock: true,
        isHideStock: true,
        isUseSku: true,
        isEnabled: true,
        detail: true,
        category: {
          select: {
            id: true,
            title: true,
          },
        },
        publisher: {
          select: {
            id: true,
            name: true,
            logo: true,
          },
        },
        creator: {
          select: {
            id: true,
            name: true,
            logo: true,
          },
        },
      },
    )) as any;
    if (!data) {
      return halt('数据异常');
    }
    return ok({
      ...data,
      price: Number(data?.price),
    });
  }

  @Post('admin/query')
  async query(@Body() dto: SPUQueryDto) {
    return ok(await this.spuService.query(dto));
  }

  @Post('admin/find')
  async find(@Body() dto: SPUFindDto) {
    return ok(await this.spuService.findOne(dto.where, dto.select));
  }

  @Post('admin/create')
  async create(@Body() dto: SPUCreateDto) {
    return ok(await this.spuService.create(dto.data));
  }

  @Patch('admin/update')
  async update(@Body() dto: SPUUpdateDto) {
    return ok(await this.spuService.update(dto));
  }
}
